


from flask import Blueprint, request, jsonify, g
import psycopg2.extras

from db_utils.postgresql_connection import PostgreSQLConnection

# from db_utils.repositories.users_table import UsersTable
# from db_utils.repositories.tokens_table import TokensTable
from db_utils.repositories.roles_table import RolesTable
from db_utils.repositories.user_roles_table import UserRolesTable

from db_utils.repositories.permissions_table import PermissionsTable
from db_utils.repositories.role_permissions_table import RolePermissionsTable

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

permission_blueprint = Blueprint('permission_blueprint', __name__)


# 创建角色
@permission_blueprint.route('/create_role', methods=['POST'])
def create_role(): # def create_role(self, role_name, description):
    
    role_name = request.form.get('role_name')
    description = request.form.get('description')

    if not all([role_name, description]):
    
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        roles_table = RolesTable(conn, cursor)

        role_info_by_name = roles_table.get_role_by_name(role_name)

        if role_info_by_name:
    
            return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "角色已存在"})
        
        roles_table.create_role(role_name, description) # (True, 1)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "创建角色成功"})
    

# 更新角色
@permission_blueprint.route('/update_role', methods=['POST'])
def update_role(): # def update_role(self, role_id, role_name, description):
    
    role_id = request.form.get('role_id')
    role_name = request.form.get('role_name')
    description = request.form.get('description')

    if not all([role_id, role_name, description]):
        
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        roles_table = RolesTable(conn, cursor)

        role_info_by_id = roles_table.get_role_by_id(role_id)

        if not role_info_by_id:

            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": "角色不存在", "resultBody": None})
        
        status, e = roles_table.update_role(role_id, role_name, description) 

        if not status:
    
            return jsonify({"status": -1, "errorCode": 1003, "errorMsg": f"更新角色失败: {e}", "resultBody": None})

        else:

            return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "更新角色成功"})
    
# 删除角色
@permission_blueprint.route('/delete_role', methods=['POST'])
def delete_role(): # def delete_role(self, role_id):
    
    role_id = request.form.get('role_id')

    if not role_id:
        
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        RolesTable(conn, cursor).delete_role(role_id)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "删除角色成功"})
    
# 获取roles列表
@permission_blueprint.route('/get_roles', methods=['GET'])
def get_roles(): # def get_all_roles(self, offset=0, limit=10):
    
    offset = request.args.get('offset', 0, type=int)
    limit = request.args.get('limit', 10, type=int)

    with PostgreSQLConnection() as (conn, cursor):

        roles_table = RolesTable(conn, cursor)

        roles_list = roles_table.get_all_roles(offset, limit)

        count = roles_table.get_role_count()

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"list": roles_list, "count": count}})
    


################################用户和角色相关##############################
# 用户添加角色
@permission_blueprint.route('/add_user_role', methods=['POST'])
def add_user_role(): # def create_user_role(self, user_id, role_id):
    
    user_id = request.form.get('user_id')
    role_id = request.form.get('role_id')

    if not all([user_id, role_id]):
        
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        create_role = UserRolesTable(conn, cursor).create_user_role(user_id, role_id) 

        if not create_role[0]:
    
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": f"添加角色失败: {create_role[1]}", "resultBody": None})
        
        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "添加角色成功"})
    
# 根据用户id查询角色id列表
# def get_role_ids_by_user_id(self, user_id) -> list:
@permission_blueprint.route('/get_role_ids_by_user_id')
def get_role_ids_by_user_id():
    
    user_id = request.args.get('user_id')

    if not user_id and not user_id.isdigit():
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "参数错误", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        role_ids = UserRolesTable(conn, cursor).get_role_ids_by_user_id(user_id)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"role_ids": role_ids}})


# 根据角色id查询用户id列表
# def get_user_ids_by_role_id(self, role_id) -> list:
@permission_blueprint.route('/get_user_ids_by_role_id')
def get_user_ids_by_role_id():
    
    role_id = request.args.get('role_id')

    if not role_id and not role_id.isdigit():
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "参数错误", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        user_ids = UserRolesTable(conn, cursor).get_user_ids_by_role_id(role_id)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"user_ids": user_ids}})

# 删除用户角色
@permission_blueprint.route('/delete_user_role', methods=['POST'])
def delete_user_role(): # def delete_user_role(self, user_id, role_id):
    
    user_id = request.form.get('user_id')
    role_id = request.form.get('role_id')

    if not all([user_id, role_id]):
        
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        delete_role = UserRolesTable(conn, cursor).delete_user_role(user_id, role_id) 
        
        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "删除角色成功"})

        
    
##############################PermissionsTable 权限接口###############################################

# 创建权限
@permission_blueprint.route('/create_permission', methods=['POST'])
def create_permission(): # def create_permission(self, permission_name, permission_path, description):
    
    permission_name = request.form.get('permission_name')
    permission_path = request.form.get('permission_path')
    description = request.form.get('description')
    if not all([permission_name, permission_path, description]):

        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        permissions_table = PermissionsTable(conn, cursor)

        permission_info_by_name = permissions_table.get_permission_by_name(permission_name)

        if permission_info_by_name:
    
            return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "权限已存在"})
        
        permissions_table.create_permission(permission_name, permission_path, description)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "创建权限成功"})
    

# 删除权限
@permission_blueprint.route('/delete_permission', methods=['POST'])
def delete_permission(): # def delete_permission(self, permission_id):
    
    permission_id = request.form.get('permission_id')

    if not permission_id:
        
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        status, error_msg = PermissionsTable(conn, cursor).delete_permission(permission_id) 
        
        if not status:

            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": f"删除权限失败: {error_msg}", "resultBody": None})

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "删除权限成功"})
    
# 获取permissions列表
@permission_blueprint.route('/get_all_permissions', methods=['GET'])
def get_all_permissions(): # def get_all_permissions(self):
    
    limit = request.args.get('limit', 10, type=int)
    offset = request.args.get('offset', 0, type=int)
    with PostgreSQLConnection() as (conn, cursor):

        permissions_table = PermissionsTable(conn, cursor)

        permissions_list = permissions_table.get_all_permissions(limit, offset)

        count = permissions_table.get_permissions_count()

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"list": permissions_list, "count": count}})



# 更新权限
@permission_blueprint.route("/update_permission", methods=['POST'])

def update_permission(): # def update_permission(self, permission_id, permission_name, description):
    
    permission_id = request.form.get('permission_id')
    permission_name = request.form.get('permission_name')
    permission_path = request.form.get('permission_path')
    description = request.form.get('description')

    if not all([permission_id, permission_name, permission_path, description]):
        
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        status, error_msg = PermissionsTable(conn, cursor).update_permission(permission_id, permission_name, permission_path, description)
        
        if not status:
    
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": f"更新权限失败: {error_msg}", "resultBody": None})


        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "更新权限成功"})
    
# 根据权限id查询权限信息
@permission_blueprint.route('/get_permission_by_id')
def get_permission_by_id():
    
    permission_id = request.args.get('permission_id')

    if not permission_id and not permission_id.isdigit():
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "参数错误", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        permission_info = PermissionsTable(conn, cursor).get_permission_by_id(permission_id)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": permission_info})
    
# 根据权限路径获取权限
@permission_blueprint.route('/get_permission_by_path')
def get_permission_by_path():
    
    permission_path = request.args.get('permission_path')

    if not permission_path:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "参数错误", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        permission_info = PermissionsTable(conn, cursor).get_permission_by_path(permission_path)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": permission_info})

########################### 角色与权限关系接口 ###########################

@permission_blueprint.route('/create_role_permission', methods=['POST'])
def create_role_permission(): # def create_role_permission(self, role_id, permission_id):
    
    role_id = request.form.get('role_id')
    permission_id = request.form.get('permission_id')

    if not all([role_id, permission_id]):
        
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        role_permissions_table = RolePermissionsTable(conn, cursor)
        
        role_permissions_table.create_role_permission(role_id, permission_id) 

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "创建权限成功"})
    
# 根据角色id查询权限id列表
@permission_blueprint.route('/get_role_permissions_by_role_id')
def get_role_permissions_by_role_id():
    
    role_id = request.args.get('role_id')

    if not role_id and not role_id.isdigit():
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "参数错误", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        role_permissions_list = RolePermissionsTable(conn, cursor).get_role_permissions_by_role_id(role_id)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"list": role_permissions_list}})
    
# 根据权限id查询角色id列表
@permission_blueprint.route('/get_role_permissions_by_permission_id')
def get_role_permissions_by_permission_id():
    
    permission_id = request.args.get('permission_id')

    if not permission_id and not permission_id.isdigit():
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "参数错误", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        role_permissions_list = RolePermissionsTable(conn, cursor).get_role_permissions_by_permission_id(permission_id)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"list": role_permissions_list}})
    
# 根据角色id和权限id查询角色权限信息
@permission_blueprint.route('/get_role_permission_by_role_id_and_permission_id')
def get_role_permission_by_role_id_and_permission_id():
    
    role_id = request.args.get('role_id')
    permission_id = request.args.get('permission_id')

    if not all([role_id, permission_id]) or not all(map(lambda x: x.isdigit(), [role_id, permission_id])):
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "参数错误", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        role_permission_info = RolePermissionsTable(conn, cursor).get_role_permission_by_role_id_and_permission_id(role_id, permission_id)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": role_permission_info})
    
# 删除角色权限关系
@permission_blueprint.route('/delete_role_permission', methods=['POST'])
def delete_role_permission(): # def delete_role_permission(self, role_id, permission_id):
    
    role_id = request.form.get('role_id')
    permission_id = request.form.get('permission_id')

    if not all([role_id, permission_id]):
        
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):

        RolePermissionsTable(conn, cursor).delete_role_permission_by_role_id_and_permission_id(role_id, permission_id)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "删除权限成功"})


